<template>
  <!-- 数据权限 -->
  <div v-loading="loading" class="scopeAuto">
    <el-tabs v-if="menuTitleList.length > 0" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane
        v-for="(item, index) in menuTitleList"
        :key="item.id + index"
        :label="item.menuName"
        :name="item.id"
      >
        <vue-easy-tree
          :data="menuList"
          :props="defaultProps"
          node-key="id"
          :indent="30"
          :default-expand-all="false"
          :expand-on-click-node="false"
          :default-expanded-keys="defaultShowNodes"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span style="font-size: 14px">{{ node.label }}</span>
            <!-- @change="handleNodeClick(data)"  @dblclick.native="handleNodeDbClick(data)"  -->
            <el-radio-group v-model="data.roleScope">
              <el-radio v-for="dict in dataScopeOptions" :key="dict.value" :label="dict.value" @click.native.prevent="radioHandle(dict.value, data)" @dblclick.native.prevent="radioDbHandle(dict.value, data)">
                {{ $t(dict.label) }}
              </el-radio>
            </el-radio-group>
          </span>
        </vue-easy-tree>
      </el-tab-pane>
    </el-tabs>
    <el-empty v-else :description="$t('当前角色还未配置权限')" />

    <el-dialog :title="$t('自定义数据权限')" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" :visible.sync="openCustom" append-to-body width="500px" @close="closeCustom">
      <div style="height: calc(100% - 50px);margin-bottom: 10px">
        <vue-easy-tree
          ref="customTree"
          :data="deptOptions"
          show-checkbox
          default-expand-all
          node-key="id"
          height="400px"
          :empty-text="$t('加载中，请稍后')"
          :props="customDefaultProps"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCustom">{{ $t("确定") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { findMenuByRoleId } from '@/api/system/menu'
// import { treeselect as deptTreeselect } from '@/api/system/dept'
import VueEasyTree from '@wchbrad/vue-easy-tree'
import '@wchbrad/vue-easy-tree/src/assets/index.scss'
var time = null // 在这里定义time 为null
export default {
  name: 'SysScopeAuthority',
  components: {
    VueEasyTree
  },
  props: {
    // form表单数据, 修改角色范围的表单
    busData: {
      type: Object,
      default: () => ({})
    },
    // roleId
    permissionsId: {
      type: String,
      default: ''
    },
    // 主表默认数据权限
    parentDataScope: {
      type: String,
      default: '5'
    }
  },
  data() {
    return {
      loading: false,
      form: {},
      menuTitleList: [],
      menuList: [],
      activeName: '',
      // PC 0, app 1
      menuType: '0',
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      customDefaultProps: {
        children: 'children',
        label: 'label'
      },
      dataScopeOptions: [
        { value: '1', label: '全部' },
        { value: '6', label: '本公司' },
        { value: '3', label: '本部门' },
        { value: '4', label: '本部门及以下' },
        { value: '5', label: '仅本人' },
        { value: '2', label: '自定义' }
      ],
      openCustom: false,
      deptOptions: [],
      // 当前选中的菜单节点
      currentCustomNode: {},
      defaultShowNodes: []
    }
  },
  watch: {
    busData: {
      handler(val) {
        this.form = val
      },
      deep: true
    }
  },
  created() {
   this.initOneMenu('0')
    this.deptOptions = this.$store.state.user.deptOption
  },
  methods: {
    initOneMenu(scene) {
      this.loading = true
      this.menuType = scene
      // 获取所有一级目录的菜单
      findMenuByRoleId(this.permissionsId).then(response => {
        this.loading = false
        if (response.data) {
          this.menuTitleList = response.data
        }
        if (this.menuTitleList && this.menuTitleList.length > 0) {
          this.activeName = this.menuTitleList[0].id
          this.handleClick({ name: this.menuTitleList[0].id })
        }
      }).catch(() => {
        this.loading = false
      })
    },
    handleClick(tab) {
      const object = this.menuTitleList.find(obj => obj.id === tab.name)
      if (object) {
        this.menuList = []
        this.menuList.push(object)
        this.$nextTick(() => {
          this.defaultShowNodes.push(object.id)
        })
        this.recoverData()
      }
    },
    // 节点单机事件
    handleNodeClick(data) {
      this.currentCustomNode = data
      if (data.roleScope === '2') {
        this.handleNodeCustom(data)
      } else {
        console.log(data.roleScope, '单机事件')
        data.roleScopeCustom = ''
        this.recoverData()
      }
    },
    radioHandle(e, data) { // 可取消选中
      clearTimeout(time)
      time = setTimeout(() => {
          e === data.roleScope ? data.roleScope = '' : data.roleScope = e
          this.handleNodeClick(data)
      }, 300)
      // console.log(e, data)
    },
    radioDbHandle(e, data) {
      clearTimeout(time) // 清除
      e === data.roleScope ? data.roleScope = '' : data.roleScope = e
      this.handleNodeDbClick(data)
    },
    // 节点双击事件
    handleNodeDbClick(data) {
      this.currentCustomNode = data
      if (data.roleScope === '2') {
        this.handleNodeCustom(data)
      } else {
        console.log(data.roleScope, '双击事件')
        this.handleNodeClickSub(data, data.roleScope)
        data.roleScopeCustom = ''
        this.recoverData()
      }
    },
    // 节点双击事件 子方法
    handleNodeClickSub(data, val) {
      if (data.children) {
        data.children.forEach(item => {
          item.roleScope = val
          if (item.children) {
            this.handleNodeClickSub(item, val)
          }
        })
      }
    },
    // 自定义节点处理
    handleNodeCustom(data) {
      console.log(data)
      this.openCustom = true
      this.$nextTick(() => {
        if (data.roleScopeCustom) {
          this.$refs.customTree.setCheckedKeys(data.roleScopeCustom.split(','))
        }
      })
    },
    // 自定义页面保存
    submitCustom() {
      const customResult = this.$refs.customTree.getCheckedKeys()
      if (customResult.length <= 0) {
        this.msgInfo('不能为空, 请选择!')
      } else {
        this.currentCustomNode.roleScopeCustom = customResult.join(',')
        this.openCustom = false
        this.recoverData()
      }
    },
    // 重置页面
    recoverData() {
      var _this = this
      this.$nextTick(() => {
        _this.$emit('submitCustom', _this.menuList)
      })
      this.$forceUpdate()
    },
    closeCustom() {
      const customResult = this.$refs.customTree.getCheckedKeys()
      if (customResult.length <= 0) {
        this.currentCustomNode.roleScopeCustom = undefined
        this.currentCustomNode.roleScope = undefined
        this.recoverData()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.scopeAuto {
  margin: 0 10px;
  height: calc(100% - 50px);
  /deep/.el-tabs {
    height: 100%;
  }
  /deep/.el-tabs__content{
    height: calc(100% - 50px);
    overflow: auto;
  }
  .el-tree-node__content{
    height: 30px;
  }
  /deep/.el-radio-group{
    margin-left: 10px;
    .el-radio{
      margin-right: 20px;
      .el-radio__label{
        padding-left: 0;
        font-size: 13px;
      }
    }
  }
}
/deep/.el-radio__input.is-checked .el-radio__inner::after,
/deep/.el-radio__inner::after{
  transition: none!important;
  // transform: none!important;
}
/deep/ .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner{
  box-shadow: none!important;
}
</style>
